import axios from 'axios'
import NProgress from 'nprogress'
import useUserStore from '@/store/user.js'
import router from '@/router/index'
import { ElMessage } from 'element-plus'

// 添加loading效果
let loading = null

const request = axios.create({
  // baseURL: 'http://127.0.0.1:80',
  timeout: 5000,
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    NProgress.start()
    loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      fullscreen: true,
      background: 'rgba(0, 0, 0, 0.7)',
    })
    // 获取token
    const user = useUserStore()
    const token = user.token
    config.headers = { Authorization: token }
    const identity = user.user?.identity
    const account = user.user?.account
    if (!config.params) {
      config.params = {}
    }
    if (identity) {
      config.params['identity'] = identity
      config.params['account'] = account
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    NProgress.done()
    if (response.data.code == 501) {
      const user = useUserStore()
      user.loginOut()
      router.push({ path: '/login' })
    }
    loading.close()
    return response.data
  },
  (error) => {
    loading.close()
    return Promise.reject(error)
  }
)

export default request
